package com
{
	import Box2D.Common.Math.b2Vec2;
	import Box2D.Dynamics.Controllers.b2BuoyancyController;
	import Box2D.Dynamics.Controllers.b2ConstantAccelController;
	import Box2D.Dynamics.Controllers.b2Controller;
	import Box2D.Dynamics.Joints.b2MouseJoint;
	import Box2D.Dynamics.Joints.b2MouseJointDef;
	import Box2D.Dynamics.b2Body;
	import Box2D.Dynamics.b2TimeStep;
	
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	public class ClickDemo extends Demo
	{
		private var m_controller:b2Controller;
		
		public var the_arrow_angle:Number;
		public var charging:Boolean=false;
		public var power:int=0;
		public var impulse:Boolean=false;
		public function ClickDemo(s:Sprite)
		{
			super(s);
			var bc:b2ConstantAccelController = new b2ConstantAccelController();
			m_controller = bc;
			bc.A = new b2Vec2(0, 0);
			var b2t:b2TimeStep = new b2TimeStep();
			b2t.dtRatio = 100;
			b2t.dt = 100;
			bc.Step(b2t);
//			bc.
//			bc.normal.Set(0,-1);
//			bc.offset = -200 / m_physScale;
//			bc.density = 100.0;
//			bc.linearDrag = 5;
//			bc.angularDrag = 2;
			
			var count:uint = m_world.GetBodyCount();
			var body:b2Body = m_world.GetBodyList();
			for(var i:uint = 0; i < count; ++i, body.GetNext()){
				m_controller.AddBody(body);
			}
			
			
			m_world.AddController(m_controller);
			s.stage.addEventListener(MouseEvent.CLICK, clickHandler, false, 0, true);
		}
		
		private function clickHandler(e:MouseEvent):void{
			_mouseX = e.stageX - s.x;
			_mouseY = e.stageY - s.y;
			mouseXWorldPhys = (_mouseX)/m_physScale; 
			mouseYWorldPhys = (_mouseY)/m_physScale; 
			var body:b2Body = GetBodyAtMouse();
			
			if (body)
			{
				body.ApplyImpulse(new b2Vec2(500 + Math.random() * 1000, 500 + Math.random() * 1000), body.GetWorldCenter());
			}
		}
		
		override protected function run(e:Event):void{
			super.run(e);
			
			s.graphics.lineStyle(1,0x0000ff,1);
			s.graphics.moveTo(5,200);
			s.graphics.lineTo(635,200);
			//It's not water without transparency...
			s.graphics.lineStyle();
			s.graphics.beginFill(0x0000ff,0.2);
			s.graphics.moveTo(5,200);
			s.graphics.lineTo(635,200);
			s.graphics.lineTo(635,355);
			s.graphics.lineTo(5,355);
			s.graphics.endFill();
		}
	}
}